package com.unitechs.controller.excel;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Controller
public class ExcelController {

    @GetMapping("/preview")
    public String previewExcel(Model model) throws IOException {
        // 生成Excel数据
        Workbook workbook = createExcelWorkbook();

        // 将Workbook传递给Thymeleaf模板
        model.addAttribute("workbook", workbook);

        return "excel-preview";
    }

    private Workbook createExcelWorkbook() throws IOException {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Sheet 1");

        // 示例数据
        List<List<String>> data = Arrays.asList(
                Arrays.asList("Name", "Age", "City"),
                Arrays.asList("John Doe", "25", "New York"),
                Arrays.asList("Jane Doe", "30", "San Francisco"),
                Arrays.asList("Bob Smith", "22", "Los Angeles")
        );

        int rowNum = 0;
        for (List<String> rowData : data) {
            Row row = sheet.createRow(rowNum++);
            int cellNum = 0;
            for (String cellData : rowData) {
                Cell cell = row.createCell(cellNum++);
                cell.setCellValue(cellData);
            }
        }

        return workbook;
    }
}
